﻿using SequentialGuid;
using Snowflake.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace Report_Unity.Unitys
{
    public class IDGeneratorUtils
    {
        #region 生成简短的Guid
        private static readonly char[] BASE36 = {
                                  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                                  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                                  'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                                  'u', 'v', 'w', 'x', 'y', 'z'
                              };

        private static string ToBase36String(byte[] toConvert, bool bigEndian = false)
        {
            if (bigEndian) Array.Reverse(toConvert); // !BitConverter.IsLittleEndian might be an alternative
            BigInteger dividend = new BigInteger(toConvert);
            var builder = new StringBuilder();
            while (dividend != 0)
            {
                BigInteger remainder;
                dividend = BigInteger.DivRem(dividend, 36, out remainder);
                builder.Insert(0, BASE36[Math.Abs(((int)remainder))]);
            }
            return builder.ToString();
        }

        public static Guid NewGuid()
        {
            // 有序的Guid
            return SequentialSqlGuidGenerator.Instance.NewGuid();

        }

        public static String NewShotGuid()
        {
            // 有序的Guid
            return ToBase36String(SequentialSqlGuidGenerator.Instance.NewGuid().ToByteArray());
        }

        /// <summary>
        /// 根据GUID获取19位的唯一数字序列(从大到小)
        /// </summary>
        /// <returns></returns>
        private static long GuidToLongID()
        {
            byte[] buffer = SequentialSqlGuidGenerator.Instance.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

        public static string Guid16StringID()
        {
            byte[] buffer = SequentialSqlGuidGenerator.Instance.NewGuid().ToByteArray();
            long lo = BitConverter.ToInt64(buffer, 0);

            return string.Format("{0:x}", lo);
        }

        #endregion

        #region 雪花算法
        // WorkerId和DatacenterId在单机中随意，0-31
        private static IdWorker worker = new IdWorker(0, 0);

        public static long NewWorkid()
        {
            return worker.NextId();
        }

        public static string Long16StringID()
        {
            return string.Format("{0:x}", NewWorkid());
        }

        #endregion
    }
}
